package com.neo.sk.collector

import akka.actor.{Actor, Props}
import com.neo.sk.common.{SaveFinishTagUrl, FinishFetchByTag, UrlTask, Launcher}
import com.neo.sk.models.{MovieSimpleDetail, MovieUrl}
import com.neo.sk.util.http.{DoubanLogin, HttpClientUtil}
import org.apache.http.impl.client.CloseableHttpClient
import org.slf4j.LoggerFactory
import scala.concurrent.duration._
import scala.util.matching.Regex

/**
 * User: Huangshanqi
 * Date: 2015/7/15
 * Time: 9:44
 */
class FetchMovieDetailManager extends Actor{
  /**
   * 访问移动版的豆瓣电影
   * http://movie.douban.com/subject/6874403/mobile
   */
  private val logger = LoggerFactory.getLogger(this.getClass)
  import com.neo.sk.collector.Manager.myExecutionContext
  private val userClient: CloseableHttpClient = HttpClientUtil.getHttpClient(DoubanLogin.Mylogin(),200)


  val undoMids = MovieUrl.getAllMid.diff(MovieSimpleDetail.getAllMid)

  private val totalMidNum = undoMids.length
  private var currentMidNum = 0

  private final val fetchMovieDetailActorNumber = 1
  private val fetchMovieDetailActors = (0 until fetchMovieDetailActorNumber).map{
    i=>
      context.actorOf(Props[FetchMovieDetailActor](new FetchMovieDetailActor(userClient)), "FetchMovieDetailActor-" + i + "-" + System.currentTimeMillis())
  }

  override def receive: Receive = {
    case Launcher =>{
      //http://api.douban.com/v2/movie/25723907
      logger.info("start fetch movie detail...........................")
      fetchMovieDetailActors.foreach{
        slave =>
          val currentMid = undoMids(currentMidNum)
          val currentUrl = "http://api.douban.com/v2/movie/"+ currentMid + "?retry=1"
          slave ! UrlTask(currentUrl)
          logger.info(">" * 10 + "total=" + totalMidNum+ ",current=" + currentMidNum + "<" * 10)
          currentMidNum += 1
      }
    }
    case FinishFetchByTag(url) =>{
      logger.info("finish=> " + url)
      val slave = sender()
      if(currentMidNum < totalMidNum){
        val currentMid = undoMids(currentMidNum)
        val currentUrl = "http://api.douban.com/v2/movie/"+ currentMid + "?retry=1"
//        sender() ! UrlTask(currentUrl)
        context.system.scheduler.scheduleOnce(10 seconds,slave,UrlTask(currentUrl))
        logger.info(">" * 10 + "total=" + totalMidNum+ ",current=" + currentMidNum + "<" * 10)
        currentMidNum += 1
      }else{
        logger.info("finish all Url list========================================")
      }
    }
    case unknow@_ => logger.info("unknow message: "+ unknow + "  in " + context.self.path.name + " from " + context.sender().path.name)
  }
}
